/*
 * DeleteUserServlet.java
 * 作用：管理员后台的用户删除控制器，负责处理删除指定用户的请求，并包含不能删除管理员自己的逻辑。
 */
package com.campustradingwall.controller.admin;

import com.campustradingwall.dao.UserDao;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/admin/deleteUser")
public class DeleteUserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        String userIdStr = request.getParameter("userId");

        if (userIdStr == null) {
            session.setAttribute("message", "无效的操作请求。");
            response.sendRedirect(request.getContextPath() + "/admin/users");
            return;
        }

        try {
            int userId = Integer.parseInt(userIdStr);
            if (currentUser.getId() == userId) {
                session.setAttribute("message", "您不能删除自己的账户。");
                response.sendRedirect(request.getContextPath() + "/admin/users");
                return;
            }

            UserDao userDao = new UserDao();
            userDao.deleteUser(userId);
            session.setAttribute("message", "用户已成功删除。");

        } catch (NumberFormatException e) {
            session.setAttribute("message", "无效的用户ID。");
        } catch (Exception e) {
            session.setAttribute("message", "删除用户时发生错误：" + e.getMessage());
        }

        response.sendRedirect(request.getContextPath() + "/admin/users");
    }
} 